package com.yonyou.pmclouds.trialinfo.jobhandler;

import com.yonyou.pmclouds.basecom.conf.TrialInfoServerProperties;
import com.yonyou.pmclouds.job.AbstractJobExecutor;
import com.yonyou.pmclouds.job.ExecResult;
import com.yonyou.pmclouds.job.JobExecutor;
import com.yonyou.pmclouds.trialinfo.entity.TrialInfoVO;
import com.yonyou.pmclouds.trialinfo.mapper.TrialInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
@JobExecutor(value = "ExpirationReminderJob")
public class ExpirationReminderJob extends AbstractJobExecutor {

    @Autowired
    private TrialInfoServerProperties trialInfoServerProperties;
    @Autowired
    private TrialInfoMapper mapper;
    @Autowired
    private JavaMailSender mailSender;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public ExecResult<String> execute(String s) {

        Calendar curr = Calendar.getInstance();
        Date currTime = curr.getTime();

        curr.add(Calendar.DAY_OF_MONTH,trialInfoServerProperties.getReminder_days());
        Date endTime = curr.getTime();
        // FIXME SimpleDateFormat的线程安全性，虽然 这里一般是单线程
        String beginDate = sdf.format(currTime)+" 00:00:00";
        String endDate = sdf.format(endTime)+" 23:59:59";

        List<TrialInfoVO> reminderList = mapper.queryTrialInfoByPeriod(beginDate,endDate);

        if(reminderList == null || reminderList.size() == 0)
            return SUCCESS;

        String mailTemplate = getEmailFromResource(trialInfoServerProperties.getReminder_email());

        int sendNum = 0;
        for(TrialInfoVO trialInfoVO : reminderList){
            String emailInfo = mailTemplate;
            MimeMessage mes = mailSender.createMimeMessage();
            MimeMessageHelper helper = null;
            try {
                helper = new MimeMessageHelper(mes,true,"utf-8");
                helper.setFrom("yygcy@yonyou.com");
                helper.setTo(trialInfoVO.getEmail());
                helper.setSubject("友工程试用到期提醒");

                long betweenDays = daysBetween(trialInfoVO.getEndtime(),currTime);

                emailInfo = emailInfo.replace("${expiration}",sdf.format(trialInfoVO.getEndtime()));
                emailInfo = emailInfo.replace("${activeUrl}",trialInfoServerProperties.getActive_url());
                if(betweenDays == 0){
                    emailInfo = emailInfo.replace("${remainInfo}","已到期");
                }else{
                    emailInfo = emailInfo.replace("${remainInfo}","剩余"+betweenDays+"天到期");
                }
                helper.setText(emailInfo,true);
                mailSender.send(mes);
                sendNum++;
            } catch (Exception e) {
                log.error(e.getMessage());
                logger.log("试用到期提醒邮件发送错误，具体信息为："+e.getMessage());
            }
        }

        logger.log("试用到期提醒邮件应发送"+reminderList.size()+",实际发送"+sendNum);

        if(sendNum != reminderList.size())
            return AbstractJobExecutor.FAIL;
        return SUCCESS;
    }

    private  long daysBetween(Date beginDate, Date endDate) {
        String expirationDate = sdf.format(endDate);
        String currDate = sdf.format(beginDate);
        long difference = 0;
        try {
            difference = ( sdf.parse(expirationDate).getTime()-sdf.parse(currDate).getTime())/86400000;
        } catch (Exception e) {
            log.error(e.getMessage());
            logger.log(e);
        }
        return Math.abs(difference);
    }


    /**
     * 从静态资源文件中获取邮件内容
     * @return
     */
    private String getEmailFromResource(String filePath) {

        StringBuffer messageBuffer = new StringBuffer();

        InputStreamReader stream = null;
        try {
            stream = new InputStreamReader(getClass().getClassLoader().getResourceAsStream(filePath),"utf-8");
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage());
        }

        BufferedReader br = null;
        try {
            br = new BufferedReader(stream);
            String line = null;
            while((line = br.readLine() ) != null){
                messageBuffer.append(line);
            }
        } catch (Exception e) {
            log.error("读取文件信息失败，具体信息为："+e.getMessage());
        }finally {
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    log.error("关闭文件流失败，具体信息为："+e.getMessage());
                }
            }
        }

        return messageBuffer.toString();
    }
}
